package springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.zb.springcloud.entities.CommonResult;
import com.zb.springcloud.entities.Payment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import springcloud.feiginservice.PaymentService;

import javax.annotation.Resource;

@RestController
public class CircleBreakerController {

    public static final String SERVICE_URL = "http://nacos-payment-provider";
    @Resource
    private PaymentService paymentService;

    @Resource
    private RestTemplate restTemplate;
    @GetMapping("/consumer/fallback/{id}")
//@SentinelResource(value = "fallback",fallback = "handlerFallback")
    @SentinelResource(value = "fallback",blockHandler = "blockHandler",fallback = "handlerFallback",exceptionsToIgnore ={IllegalArgumentException.class} )
    public CommonResult<Payment> fallback(@PathVariable Long id){
        CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id);
        if (id == 4){
            throw new IllegalArgumentException("IllegalArgumentException....非法参数");
        }else if (result.getData() == null){
            throw new NullPointerException("IllegalAccessException....空指针异常");
        }
        return result;
    }

    public CommonResult<Payment> handlerFallback(@PathVariable Long id, Throwable e){
        Payment payment = new Payment(id , null);
        return new CommonResult<>(444, "兜底异常handlerFallback,exception内容  ：" +e.getMessage(),payment);
    }
public CommonResult<Payment> blockHandler(@PathVariable Long id, BlockException e){
    Payment payment = new Payment(id , null);
    return new CommonResult<>(445, "BlockException限流,无此流水，BlockException限流  ：" +e.getMessage(),payment);
}

@GetMapping(value = "/consumer/paymentSQL/{id}")
@SentinelResource(value = "paymentSQL",blockHandler = "blockHandler")
    public CommonResult<Payment> paymentSQL(@PathVariable Long id){
        return paymentService.paymentSQL(id);
    }
}
